<template>
  <div>
    <el-header
      style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
      <div>
        <svg-icon class="primary" :icon-class="$route.meta.icon"/>
        <span class="primary">{{$route.meta.title}}</span>
      </div>
      <div class="header-button-container">
        <el-button :icon="queryType? 'el-icon-search':'el-icon-close'" type="primary"
                   @click="chooseClick">{{queryType == false?'隐藏':'查询'}}
        </el-button>
        <el-button icon="el-icon-plus" type="info" style="margin-left: 10px" @click="addClick">新增消息
        </el-button>
        <el-button @click="handleDownload" type="info" icon="el-icon-plus">导出</el-button>
      </div>
    </el-header>
    <div class="pd10">
      <div style="margin-bottom: 10px;display: flex;align-items: center" v-show="queryType == false">
        <el-input prefix-icon="el-icon-search" placeholder="消息标题" style="width: 200px"
                  v-model="query.msgTitle"></el-input>
        <el-input prefix-icon="el-icon-search" placeholder="状态" style="width: 200px;margin-left: 10px"
                  v-model="query.status"></el-input>
        <el-button style="margin-left: 10px" icon="el-icon-search" type="primary" @click="queryClick">查询
        </el-button>
        <el-button style="margin-left: 10px" icon="el-icon-refresh-right" type="info" @click="resetClick">重置
        </el-button>
      </div>
      <el-table
        :data="sysMsgData"
        border
        stripe
        style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="50"
          fixed>
        </el-table-column>
        <el-table-column
          prop="msgTitle"
          label="消息标题"
          align="center">
        </el-table-column>
        <el-table-column
          prop="msgContent"
          label="消息内容"
          min-width>
        </el-table-column>
        <el-table-column
          prop="isAttac"
          label="附件"
          align="center"
          width="80">
        </el-table-column>
        <el-table-column
          prop="msgLevel"
          label="内容级别"
          align="center"
          width="80">
          <template slot-scope="scope">
               <span>
              {{ scope.row.msgLevel | formatMsgLevel}}
               </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="msgType"
          label="内容类型"
          align="center"
          width="80">
          <template slot-scope="scope">
               <span>
              {{ scope.row.msgType | formatMsgType}}
               </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="receiveType"
          label="接收者类型"
          align="center"
          width="100">
          <template slot-scope="scope">
               <span>
              {{ scope.row.receiveType | formatReceiveType}}
               </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="80">
          <template slot-scope="scope">
               <span>
              {{ scope.row.status | formatStatus}}
               </span>
          </template>
        </el-table-column>
        <el-table-column
          label="功能"
          align="center"
          prop="remark"
          width="80"
          fixed="right"
        >
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="发送" placement="top-start">
            <el-button@click="sendClick(scope.row)" type="primary" size="mini">发送</el-button>
          </el-tooltip>
        </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="80">
          <template slot-scope="scope">
            <div style="display: flex; justify-content: center;">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                <a @click="editClick(scope.row)"><i style="color: #409EFF" class="el-icon-edit" /></a>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <a style="margin-left: 10px" @click="deleteMsg(scope.row)"><i style="color: #F56C6C" class="el-icon-delete" /></a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="请选择消息接收者"
      width="50%"
      :visible.sync="dialogVisible">
      <el-row>
        <el-col :span="12">
          <el-tree
            ref="treeOne"
            :data="treeOne"
            :props="props"
            node-key="name"
            :load="loadTreeOne"
            lazy
            default-expand-all
            show-checkbox
          >
          </el-tree>
        </el-col>
        <el-col :span="12">
          <el-tree
            ref="treeTwo"
            :data="treeTwo"
            :props="props"
            node-key="name"
            :load="loadTreeTwo"
            lazy
            default-expand-all
            show-checkbox
          >
          </el-tree>
        </el-col>
      </el-row>
      <!--      <div v-for="item in treeData"><span>{{item}}</span></div>-->
      <el-row>
        <el-button type="primary" style="margin-left: 10px" @click="sendSysMsg">发送消息</el-button>
      </el-row>
    </el-dialog>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadMsg"></pagination>
    </el-footer>
  </div>
</template>
<script>
  import {sendMsg, list, del, find} from '@/api/sysMsg'
  import {list as listPost} from '@/api/sysPost'
  import {list as listOffice} from '@/api/sysOffice'
  import {EventBus} from '@/api/eventBus'
  import Pagination from '@/components/Pagination';
  export default {
    name: 'sysMsg-list',
    data() {
      return {
        treeOne: [],
        treeTwo: [],
        // office:[],
        // post:[]

        sysMsgData: [],
        sysMsgId: '',
        dialogVisible: false,
        props: {
          label: 'name',
          children: 'children'
        },
        office: [],
        post: [],
        msgLevels: [ // 数据源
          {value: 1, label: '普通'},
          {value: 2, label: '一般'},
          {value: 3, label: '紧急'},
        ],
        msgTypes: [ // 数据源
          {value: 1, label: '公告'},
          {value: 2, label: '新闻'},
          {value: 3, label: '会议'},
          {value: 4, label: '通知'}
        ],
        receiveTypes: [ // 数据源
          {value: 0, label: '全部'},
          {value: 1, label: '用户'},
          {value: 2, label: '部门'},
          {value: 3, label: '角色'},
          {value: 4, label: '岗位'}
        ],
        statuss: [ // 数据源
          {value: 0, label: '草稿'},
          {value: 1, label: '审核'},
          {value: 2, label: '驳回'},
        ],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
          msgTitle: '',
          status: ''
        },
        keyword: {
          msgTitle: '',
          status: ''
        },
        form: {}
      }
    },
    components: {Pagination},
    filters: {
      formatMsgLevel(value) {
        if (value === 1) {
          return '普通'
        } else if (value === 2) {
          return '一般'
        } else if (value === 3) {
          return '紧急'
        }
      },
      formatMsgType(value) {
        if (value === 1) {
          return '公告'
        } else if (value === 2) {
          return '新闻'
        } else if (value === 3) {
          return '会议'
        } else if (value === 4) {
          return '通知'
        }
      },
      formatReceiveType(value) {
        if (value === "0") {
          return '全部'
        } else if (value === "1") {
          return '用户'
        } else if (value === "2") {
          return '部门'
        } else if (value === "3") {
          return '角色'
        } else if (value === "4") {
          return '岗位'
        }
      },
      formatStatus(value) {
        if (value === 0) {
          return '草稿'
        } else if (value === 1) {
          return '审核'
        } else if (value === 2) {
          return '驳回'
        }
      },

    },
    created() {
      this.loadMsg()
      EventBus.$on('sysMsg-add', res => { // 监听新增完毕
        // 更新列表数组
        this.sysMsgData.splice(0, 0, res)
      });
      EventBus.$on('sysMsg-edit', res => { // 监听新增完毕
        // 更新列表数组
        for (var i = 0; i < this.sysMsgData.length; i++) {
          if (this.sysMsgData[i].id == res.id) {
            this.$set(this.sysMsgData, i, res)
          }
        }
      })
    },
    methods: {
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220//减去页面上固定高度height
        }
      },
      handleDownload() {

      },
      queryClick() {
        this.keyword = this.query;
        this.pageNum = 1
        this.loadMsg()
        console.log(this.keyword.msgTitle)
      },
      resetClick() {
        this.query.msgTitle = '';
        this.query.status = '';
        this.keyword = {}
        this.pageNum = 1;
        this.loadMsg()
      },
      loadMsg() {
        let params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', this.pageSize)
        params.append('msgTitle', this.keyword.msgTitle)
        params.append('status', this.keyword.status)
        list(params).then(response => {
          console.log(response)
          this.sysMsgData = response.data.data
          this.total = response.data.total
        }).catch(error => {
          console.log(error)
        });
      },
      addClick() {
        this.$router.push({
          path: '/sysMsg/add'
        })
      },
      sendSysMsg() {
        let res1 = this.$refs.treeOne.getCheckedNodes()
        let res2 = this.$refs.treeTwo.getCheckedNodes()
        console.log(res1, 'res1')
        console.log(res2, 'res2')
        let officeIds = []
        let postIds = []
        for (var i = 0; i < res1.length; i++) {
          officeIds.push(res1[i].id)
        }
        for(var i = 0;i<res2.length;i++){
          postIds.push(res2[i].id)
        }
        this.form.officeIds = officeIds
        this.form.postIds = postIds
        find(this.sysMsgId).then(res => {
          console.log(res)
          let params = new URLSearchParams()
          if (this.form.officeIds.length > 0) {
            params.append('officeIds', this.form.officeIds)
          }
          if (this.form.postIds.length > 0) {
            params.append('postIds', this.form.postIds)
          }
          sendMsg(res.data.sysMsg, params).then(response => {
            console.log(response)
          })
        })
      },
      editClick(row) {
        this.$router.push({
          path: '/sysMsg/edit', query: {id: row.id}

        })
      },
      deleteMsg(data) {
        console.log(data)
        var _this = this
        this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(_this.sysMsgData, '888')
          del(data.id).then(response => {
            console.log(response)
            _this.sysMsgData.forEach(function (item, index) {
              if (item.id == data.id) {
                _this.sysMsgData.splice(index, 1)
              }
            });
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log(error)
          })
        }).catch(() => {
        });
      },
      loadTreeOne(node, resolve) {
        if (node.level === 0) {
          return resolve([{name: '部门'}])
        }
        if (node.level > 1) return resolve([]);
        setTimeout(() => {
          if (node.data.name === '部门') {
            listOffice().then(res => {
              if (res.data) {
                this.treeOne.office = res.data
                console.log(res.data, '部门')
                this.office = res.data
                console.log(this.office, 'office')
                return resolve(res.data)
              } else {
                console.log('error')
              }
            })
          }
        }, 100);
      },
      loadTreeTwo(node, resolve) {
        if (node.level === 0) {
          return resolve([{name: '岗位'}])
        }
        if (node.level > 1) return resolve([]);
        setTimeout(() => {
          if (node.data.name === '岗位') {
            listPost().then(res => {
              console.log(res, '岗位res')
              if (res.data) {
                this.treeTwo.post = res.data
                console.log(res.data, '岗位')
                this.post = res.data.data
                console.log(this.post, 'post')
                return resolve(res.data.data)
              } else {
                console.log('error', '777')
              }
            })
          }
        }, 100);
      },
      sendClick(row) {
        this.dialogVisible = true
        this.sysMsgId = row.id
        console.log(this.sysMsgId)
        // listOffice().then(res => {
        //   // this.$set(this.treeData, 'office', res.data)
        //   this.$set(this.office, res.data)
        // }).catch(err => {
        //   console.log(err)
        // })
        // listPost().then(res => {
        //   console.log(res)
        //   this.$set(this.post, res.data.data)
        // }).catch(err => {
        //   console.log(err)
        // })
      },
    }
  }
</script>
<style scoped>
</style>
